package me.android.library.utils.android;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class StorageUtil {

    /**
     * 获取SD卡绝对路径
     */
    public String getExternalStoragePath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    /**
     * 获取App 图片缓存路径
     */
    public String getImageCachPath() {
        return String.format("%s/%s", getCachPath(), "image");
    }

    /**
     * 获取App缓存路径
     */
    public String getCachPath() {
        File dir = getCachDir();
        return dir.getPath();
    }

    /**
     * 获取App缓存目录
     */
    public File getCachDir() {
        Context cx = ContextUtil.getAppContext();

        File file = null;
        if (StorageUtil.existSDCard()) {
            file = cx.getExternalCacheDir();
        }

        if (file == null) {
            file = cx.getCacheDir();
        }

        return file;
    }

    public boolean existSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public List<StorageVolume> getStorageVolumes() {
        StorageManager storageManager = SystemServiceUtil.getStorageManager();
        return storageManager.getStorageVolumes();
    }


    /**
     * 通过 File 和 StatFs 获取容量（API 24+）
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    public VolumeInfo getVolumeSize(StorageVolume volume) {
        Context cx = ContextUtil.getAppContext();
        String label = volume.getDescription(cx);
        long totalSize = 0;
        long availableSize = 0;

        File directory = volume.getDirectory();
        if (directory != null && directory.exists()) {
            StatFs statFs = new StatFs(directory.getPath());
            long blockSize = statFs.getBlockSizeLong();
            long totalBlocks = statFs.getBlockCountLong();
            long availableBlocks = statFs.getAvailableBlocksLong();

            totalSize = totalBlocks * blockSize;
            availableSize = availableBlocks * blockSize;
        }
        return new VolumeInfo(label, volume.isPrimary(), totalSize, availableSize);
    }

    /**
     * 判断外部存储是否可写
     *
     * @return true：外部存储已挂载且可读写；false：未挂载、只读或不可用
     */
    public boolean isExternalStorageWritable() {
        // 获取外部存储的状态
        String state = Environment.getExternalStorageState();
        // 状态为 MEDIA_MOUNTED 表示已挂载且可读写
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    /**
     * 扩展：判断外部存储是否可读（包含只读状态）
     *
     * @return true：外部存储已挂载（可读写或只读）；false：未挂载或不可用
     */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        // 可读状态包括：可读写（MEDIA_MOUNTED）或只读（MEDIA_MOUNTED_READ_ONLY）
        return Environment.MEDIA_MOUNTED.equals(state)
                || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }


    @Getter
    @AllArgsConstructor
    public static class VolumeInfo {
        String label;
        boolean isPrimary;
        long totalSize;
        long availableSize;
    }
}






